<template>
  <div class="baseinfo" style="padding-bottom: 70px">
    <a-form-model ref="ruleForm" :model="form" :rules="rules" :label-col="labelCol" :wrapper-col="wrapperCol">
      <div>
        <div class="info-title">
          <img src="@/assets/category-blue.png" alt="" />
          <span>基本信息</span>
        </div>
        <a-row :gutter="24">
          <a-col :span="8">
            <a-form-model-item label="项目编号" prop="projectNo" :label-col="{ span: 8 }" :wrapper-col="{ span: 15 }">
              <a-input v-model="form.projectNo" :disabled="true" />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item
              ref="projectName"
              label="项目名称"
              prop="projectName"
              :label-col="{ span: 8 }"
              :wrapper-col="{ span: 15 }"
            >
              <a-input
                v-model="form.projectName"
                @blur="
                  () => {
                    $refs.projectName.onFieldBlur()
                  }
                "
                placeholder="请输入有效的项目名称"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item
              label="项目分类"
              prop="projectTypeSubCategory"
              :label-col="{ span: 8 }"
              :wrapper-col="{ span: 15 }"
            >
              <a-input
                v-model="form.projectTypeSubCategory"
                placeholder="请答题判断"
                @click="subType.visible = true"
                readOnly
                :disabled="form.id != ''"
                v-if="form.projectTypeSubCategory != 'S'"
              />
              <span v-if="form.projectTypeSubCategory == 'S'"
                ><span style="color: #f7a961; margin: 0 6px; font-size: 16px">{{ subName }}</span></span
              >
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row :gutter="24">
          <a-col :span="8">
            <a-form-model-item label="立项方式" prop="projectMode" :label-col="{ span: 8 }" :wrapper-col="{ span: 15 }">
              <a-radio-group v-model="form.projectMode" :options="projectModeOptions" :disabled="form.status > 1">
              </a-radio-group>
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item
              ref="hatchProjectNo"
              label="动议编号"
              :label-col="{ span: 8 }"
              :wrapper-col="{ span: 15 }"
            >
              <a-input
                v-model="form.hatchProjectNo"
                placeholder="请选择"
                @click="hatch.visible = true"
                :disabled="form.status > 1"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="8">
            <a-form-model-item
              ref="hatchProjectName"
              label="动议名称"
              :label-col="{ span: 8 }"
              :wrapper-col="{ span: 15 }"
            >
              <a-input v-model="form.hatchProjectName" :disabled="true" />
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row :gutter="24" v-if="!changeId">
          <a-col :span="16">
            <a-form-model-item
              ref="implementPlace"
              label="实施地点"
              prop="implementPlace"
              :label-col="{ span: 3 }"
              :wrapper-col="{ span: 21 }"
            >
              <a-input
                v-model="form.implementPlace"
                @blur="
                  () => {
                    $refs.implementPlace.onFieldBlur()
                  }
                "
                placeholder="请填写"
              />
            </a-form-model-item>
          </a-col>
          <a-col :span="8" v-if="form.projectTypeSubCategory != 'S'">
            <a-form-model-item ref="sourceWbsNo" label="原WBS号" :label-col="{ span: 8 }" :wrapper-col="{ span: 15 }">
              <a-input v-model="form.sourceWbsNo" placeholder="搬迁项目时填写" />
            </a-form-model-item>
          </a-col>
          <a-col :span="8" v-if="form.projectTypeSubCategory == 'S'">
            <a-form-model-item
              label="签订相关协议"
              prop="resultOperationPlan"
              :label-col="{ span: 8 }"
              :wrapper-col="{ span: 15 }"
            >
              <a-radio-group
                v-model="form.resultOperationPlan"
                title="如已有销售合同/中标通知书/框架协议等相关协议约定，请选“是”；反之选“否”"
              >
                <a-radio :value="'1'">是</a-radio>
                <a-radio :value="'2'">否</a-radio>
              </a-radio-group>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row :gutter="24" v-if="!changeId">
          <a-col :span="16">
            <a-form-model-item
              ref="projectScope"
              label="项目范畴"
              prop="projectScope"
              :label-col="{ span: 3 }"
              :wrapper-col="{ span: 21 }"
            >
              <a-tooltip :overlayStyle="{ width: '20%' }">
                <div style="display: flex; align-items: center">
                  <a-select v-model="form.projectScope">
                    <a-select-option
                      v-for="(item, index) in codes['工程立项项目范畴']"
                      :key="'projectScope' + index"
                      :value="item.code"
                    >
                      {{ item.parentid }}
                    </a-select-option>
                  </a-select>
                  <span class="icon iconfont icon-wenhao"></span>
                </div>
                <template #title>
                  <div>调味品类（酱油、酱、醋、鸡精等）及产供、物流、代代田等相关项目</div>
                  <div>非调味品类（玻璃、淀粉、鲜之然、能源、废水等）相关项目</div>
                </template>
              </a-tooltip>
            </a-form-model-item>
          </a-col>
          <a-col :span="8" v-if="form.projectTypeSubCategory != 'S'">
            <a-form-model-item
              ref="isEia"
              label="是否环评"
              prop="isEia"
              :label-col="{ span: 3 }"
              :wrapper-col="{ span: 21 }"
            >
              <a-tooltip :overlayStyle="{ width: '20%' }">
                <div style="display: flex; align-items: center">
                  <a-select v-model="form.isEia">
                    <a-select-option
                      v-for="(item, index) in codes['工程立项是否环评']"
                      :key="'isEia' + index"
                      :value="item.code"
                    >
                      {{ item.name }}
                    </a-select-option>
                  </a-select>
                  <span class="icon iconfont icon-wenhao"></span>
                </div>
                <template #title>
                  <div>是否需要环评：</div>
                  <div>以下问题满足一项即为需要环评</div>
                  <div>1、项目投产后，是否新增生产许可证的产品？</div>
                  <div>2、项目投产后，与现有生产工艺相比，是否有新增的生产工艺？（不含生产工艺参数调整）</div>
                  <div>3、项目投产后，是否有新增危险化学品的储存量或者种类？（含酒精储罐等）</div>
                </template>
              </a-tooltip>
            </a-form-model-item>
          </a-col>
          <a-col :span="8" v-if="form.projectTypeSubCategory == 'S'">
            <a-form-model-item
              label="签订相关协议"
              prop="resultOperationPlan"
              :label-col="{ span: 8 }"
              :wrapper-col="{ span: 15 }"
            >
              <a-radio-group
                v-model="form.resultOperationPlan"
                title="如已有销售合同/中标通知书/框架协议等相关协议约定，请选“是”；反之选“否”"
              >
                <a-radio :value="'1'">是</a-radio>
                <a-radio :value="'2'">否</a-radio>
              </a-radio-group>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row :gutter="24">
          <a-col :span="24">
            <a-form-model-item
              ref="projectContent"
              prop="projectContent"
              :label-col="{ span: 3 }"
              :wrapper-col="{ span: 21 }"
              class="slot-label"
            >
              <span slot="label"
                >项目概况
                <p>或立项理由:</p></span
              >
              <a-textarea
                v-model="form.projectContent"
                @blur="
                  () => {
                    $refs.projectContent.onFieldBlur()
                  }
                "
                :auto-size="{ minRows: 3, maxRows: 5 }"
                style="width: 100%"
                placeholder="请填写"
              />
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row :gutter="24">
          <a-col :span="24">
            <a-form-model-item
              ref="projectImplement"
              prop="projectImplement"
              :label-col="{ span: 3 }"
              :wrapper-col="{ span: 21 }"
              class="slot-label"
            >
              <span slot="label"
                >实施效益
                <p>及指标说明:</p></span
              >
              <a-textarea
                v-model="form.projectImplement"
                @blur="
                  () => {
                    $refs.projectImplement.onFieldBlur()
                  }
                "
                :auto-size="{ minRows: 3, maxRows: 5 }"
                style="width: 100%"
                placeholder="请填写"
              />
            </a-form-model-item>
          </a-col>
        </a-row>

        <a-row :gutter="24" v-if="form.projectTypeSubCategory == 'GE' && false">
          <a-col :span="8">
            <a-form-model-item
              label="GE项目类型"
              prop="projectMode"
              :label-col="{ span: 8 }"
              :wrapper-col="{ span: 15 }"
            >
              <a-radio-group v-model="form.additionType" :options="additionTypes" :disabled="form.status > 1">
              </a-radio-group>
            </a-form-model-item>
          </a-col>
        </a-row>
      </div>
      <div>
        <project-complete-accept-target
          ref="projectCompleteAcceptTargets"
          :projectBuildId="projectBuildId"
          :changeId="changeId"
          :editable="true"
          @doSave="doSave"
        />
      </div>

      <five-to-five
        ref="fiveForm"
        :projectBuildId="projectBuildId"
        :change-id="changeId"
        @addField="addFiveDataToForm"
      />
      <div>
        <div class="info-title">
          <span>数字贷信息</span>
        </div>
        <a-row :gutter="24">
          <a-col :span="8">
            <a-form-model-item
              label="是否数字贷"
              ref="digitalLoan"
              prop="digitalLoan"
              :label-col="{ span: 8 }"
              :wrapper-col="{ span: 15 }"
            >
              <a-radio-group v-model="form.digitalLoan" @change="handleDigitalLoanChange">
                <a-radio :value="true"> 是 </a-radio>
                <a-radio :value="false"> 否 </a-radio>
              </a-radio-group>
            </a-form-model-item>
          </a-col>
          <a-col :span="8" v-if="form.digitalLoan">
            <a-form-model-item
              label="备案证名称"
              prop="filingName"
              :label-col="{ span: 8 }"
              :wrapper-col="{ span: 15 }"
            >
              <a-select v-model="form.filingName" placeholder="请选择" :options="filingNameOptions">
                <a-icon slot="suffixIcon" type="plus" />
              </a-select>
            </a-form-model-item>
          </a-col>
        </a-row>
      </div>
    </a-form-model>

    <pagination-select
      :title="hatch.title"
      :searchPlaceholder="hatch.searchPlaceholder"
      :visible="hatch.visible"
      :url="hatch.url"
      :columns="hatch.columns"
      @hatchHandleOk="hatchHandleOk"
    />
    <sub-type-questions
      :visible="subType.visible"
      :project-class="form.projectClass"
      @subTypeHandleOk="subTypeHandleOk"
    />
  </div>
</template>
<script>
import $ from 'jquery'
import { getAction, getActionAsync, postAction, postActionAsync } from '@/api/manage'
import { getParamValFromUrl, strNotNull } from '@/utils/common.js'
import Vue from 'vue'
import SubTypeQuestions from '../../SubTypeQuestions.vue'
import { CodesMixin } from '@/mixins/CodesMixin'
export default {
  mixins: [CodesMixin],
  components: {
    PaginationSelect: () => import('@/components/tools/PaginationSelect'),
    SubTypeQuestions: () => import('@/components/tools/SubTypeQuestions'),
    ProjectCompleteAcceptTarget: () => import('@/components/tools/projectBuildStup/ProjectCompleteAcceptTarget'),
    FiveToFive: () => import('@/components/tools/projectBuildStup/baseInfo/FiveToFive'),
  },
  props: {
    projectBuildId: {
      Type: String,
      default: '',
    },
    changeId: {
      Type: String,
      default: '',
    },
    selProjectType: {
      Type: String,
      default: '',
    },
  },
  data() {
    return {
      labelCol: { span: 8 },
      wrapperCol: { span: 15 },
      other: '',
      subName: '',
      form: {
        id: '',
        projectClass: '40',
        additionType: null,
        projectNo: '',
        projectName: '',
        projectTypeSubCategory: '',
        projectMode: '',
        hatchProjectId: '',
        hatchProjectNo: '',
        hatchProjectName: '',
        sourceWbsNo: '',
        projectContent: '',
        projectImplement: '',
        implementPlace: '',
        resultOperationPlan: '',
        status: 0,
      },
      rules: {
        projectName: [
          { required: true, message: '请输入有效的项目名', trigger: 'blur' },
          { min: 1, max: 50, message: '项目名不超过50个字符', trigger: 'blur' },
        ],
        projectTypeSubCategory: [{ required: true, message: '请选择项目分类', trigger: 'change' }],
        sourceWbsNo: [{ min: 1, max: 20, message: '原项目WBS号不超过20个字符', trigger: 'blur' }],
        projectContent: [
          { required: true, message: '请输入立项理由（或项目概况）', trigger: 'blur' },
          { min: 1, max: 2000, message: '立项理由（或项目概况）不超过2000个字符', trigger: 'blur' },
        ],
        projectImplement: [
          { required: true, message: '请输入项目实施后效益及指标说明', trigger: 'blur' },
          { min: 1, max: 2000, message: '项目实施后效益及指标说明不超过2000个字符', trigger: 'blur' },
        ],
        implementPlace: [
          { required: true, message: '请输入实施地点', trigger: 'blur' },
          { min: 1, max: 150, message: '实施地点不超过150个字符', trigger: 'blur' },
        ],
        resultOperationPlan: [{ required: true, message: '请选择签订相关协议', trigger: 'blur' }],
        digitalLoan: [{ required: true, message: '请选择是否数字贷', trigger: 'change' }],
        filingName: [],
        isEia: [{ required: true, message: '请选择是否环评', trigger: 'change' }],
        projectScope: [{ required: true, message: '请选择项目范围', trigger: 'change' }],
      },
      projectModeOptions: [],
      additionTypes: [],
      url: {
        codeInfoList: '/manage/codeInfo/list',
        getProjectByNo: '/projectBuild/getProjectByNo',
        save: '/projectBuild/add',
        queryVOById: '/projectBuild/queryVOById',
      },
      hatch: {
        visible: false,
        title: '请选择动议项目',
        searchPlaceholder: '输入代码或名称查询',
        url: '/hatchProject/listBySelect',
        columns: [
          {
            title: '动议项目编号',
            dataIndex: 'hatchProjectNo',
            align: 'center',
          },
          {
            title: '动议项目名称',
            dataIndex: 'hatchProjectName',
            align: 'center',
          },
        ],
      },
      subType: {
        visible: false,
      },
      loadFinish: false,
      filingNameOptions: [],
      filingNameRule: { required: true, message: '请选择备案证名称', trigger: 'change' },
    }
  },
  computed: {},
  methods: {
    addFiveDataToForm(val, valRef) {
      this.$set(this.form, valRef, val)
    },
    handleDigitalLoanChange() {
      if (this.form.digitalLoan) {
        this.rules.filingName.push(this.filingNameRule)
      } else {
        this.rules.filingName = []
      }
    },
    async doSubmit() {
      if (!this.loadFinish) {
        layer.message.warning('请等待页面加载完毕')
        return {}
      }
      var validR = false
      // let targets = this.$refs.projectCompleteAcceptTargets.getTargets()
      // if(!targets || targets.length<=0){
      //   this.$message.warning('请至少填写一条验收竣工指标')
      //   validR = false;
      // }
      // let checkTargetFlag = false
      // for(let target of targets){
      //   if(target.descript && target.checkLogic && target.descript.trim()  && target.checkLogic.trim()){
      //     checkTargetFlag = true
      //     break
      //   }
      // }
      // if(!checkTargetFlag){
      //   this.$message.warning('请至少保证一条竣工验收[指标类型][指标说明]同时填写完成')
      //   validR = false;
      // }
      try {
        validR = await this.$refs.ruleForm.validate()
        validR = await this.$refs.fiveForm.checkFiveWriteStatus()
      } catch (e) {
        validR = false
      }
      console.log('validR', validR)
      this.form.validResult = validR

      let res = await this.doSave()
      this.projectBuildId = res
      return { valid: validR, id: res }
    },
    async doSave() {
      let flag = null
      this.form.projectCompleteAcceptTargets = this.$refs.projectCompleteAcceptTargets.data
      var formData = JSON.parse(JSON.stringify(this.form))
      formData.changeId = this.changeId
      var vm = this
      await postActionAsync(this.url.save, formData)
        .then((res) => {
          if (res.code == 200) {
            vm.form.id = res.result.id
            vm.form.projectNo = res.result.projectNo
            this.$message.success('保存成功')
            return (flag = res.result.id)
          } else {
            this.$message.warning('保存数据出错:' + res.message)
          }
        })
        .catch((res) => {
          this.$message.warning('保存数据出错:' + res.message)
        })

      return flag
    },
    resetForm() {
      this.$refs.ruleForm.resetFields()
    },
    //项目分类选项
    initProjectModeOptions() {
      var vm = this
      getAction(vm.url.codeInfoList, { type: '立项方式' }).then((res) => {
        if (res.code == 200) {
          res.result.records.forEach((element) => {
            vm.projectModeOptions.push({
              label: element.name,
              value: parseInt(element.code),
            })
          })
        } else {
          this.$message.warning('加载【立项方式】选项有误：' + res.message)
        }
      })
    },
    //初始化项目所属的品类
    initFilingNameOptions() {
      var vm = this
      getAction(this.url.codeInfoList, { type: '数字贷备案证名称' })
        .then((res) => {
          if (res.code == 200) {
            var list = res.result
            if (list != null) {
              list.records.map((item) => {
                vm.filingNameOptions.push({ value: item.name, label: item.name })
              })
            }
          } else {
            this.$message.warning('查询数字贷备案证名称失败:' + res.message)
          }
        })
        .catch((res) => {
          this.$message.warning('查询数字贷备案证名称失败:' + res.message)
        })
    },
    initAdditionTypes(subType) {
      var dicType = subType + '类试题附加类型'
      getAction(this.url.codeInfoList, { type: dicType }).then((res) => {
        if (res.code == 200) {
          this.additionTypes = []
          res.result.records.forEach((element) => {
            this.additionTypes.push({
              label: element.name,
              value: element.code,
            })
          })
        } else {
          this.$message.warning('加载【' + dicType + '】选项有误：' + res.message)
        }
      })
    },
    //动议项目选中
    hatchHandleOk(record) {
      if (record != null && record.length > 0) {
        this.form.hatchProjectId = record[0].id
        this.form.hatchProjectNo = record[0].hatchProjectNo
        this.form.hatchProjectName = record[0].hatchProjectName
      }
      this.hatch.visible = false
    },
    //项目类型选中
    subTypeHandleOk(subType) {
      this.subType.visible = false
      if (subType != null) {
        // if(!this.form.additionType && subType=='GE'){
        //   this.initAdditionTypes(subType);
        //   this.form.additionType='1'
        // }else if(subType!='GE'){
        //   this.form.additionType=null
        // }
        this.form.projectTypeSubCategory = subType
      }
    },
    //如果有id，则加载已填写信息
    initData() {
      if (this.projectBuildId != null && this.projectBuildId != '') {
        var vm = this
        getAction(this.url.queryVOById, { id: this.projectBuildId, changeId: this.changeId })
          .then((res) => {
            if (res.code == 200) {
              var result = res.result
              if (result != null) {
                this.form = result
                this.initSubName()
                this.handleDigitalLoanChange()
                this.loadFinish = true
                if (this.form.projectTypeSubCategory == 'GE') {
                  // this.initAdditionTypes(this.form.projectTypeSubCategory);
                }
              } else {
                vm.$message.warning('初始化项目信息为空')
              }
            } else {
              this.$message.warning('初始化项目信息失败:' + res.message)
            }
          })
          .catch((res) => {
            this.$message.warning('初始化项目信息失败:' + res.message)
          })
      } else {
        this.loadFinish = true
      }
    },
    initSubName() {
      var vm = this
      getAction(this.url.codeInfoList, {
        type: '项目子类',
        isdel: 0,
        parentid: vm.form.projectClass,
        code: vm.form.projectType,
      })
        .then((res) => {
          if (res.code == 200) {
            var list = res.result
            if (list != null) {
              this.subName = list.records[0].name
            }
          } else {
            this.$message.warning('项目子类:' + res.message)
          }
        })
        .catch((res) => {
          this.$message.warning('项目子类:' + res.message)
        })
    },
  },
  mounted() {
    this.fetchCodes(['工程立项项目范畴', '工程立项是否环评'])
    if ((this.projectBuildId == null || this.projectBuildId == '') && this.selProjectType == 'S') {
      this.form.projectType = this.selProjectType
      this.form.projectTypeSubCategory = this.selProjectType
      this.initSubName()
    }
    this.initProjectModeOptions()
    this.initFilingNameOptions()
    this.initData()
  },
}
</script>
<style lang="less" scoped>
/deep/ .ant-btn-primary {
  width: 85px;
  height: 30px;
  border-radius: 2px;
  background: #4095e4;
  margin-right: 10px;
}
/deep/ .default {
  width: 85px;
  height: 30px;
  border-radius: 2px;
}
.baseinfo {
  background-color: #fff;
  border: 1px solid #eaeaea;
  padding: 30px;
  .btn {
    display: flex;
    justify-content: center;
  }
}
.info-title {
  display: flex;
  align-items: center;
  margin: 10px 0;
}
.info-title > img {
  margin-right: 5px;
}
.info-title > span {
  font-size: 16px;
  font-weight: 900;
  color: black;
}
</style>
